package com.lagou.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRegistration;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/7/7 下午9:41
 */
@Component
public class MyWebApplicationInitializer implements ApplicationContextAware, WebApplicationInitializer {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    @Override
    public void onStartup(ServletContext servletContext){
        DispatcherServlet dispatcherServlet = context.getBean(DispatcherServlet.class);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", dispatcherServlet);
        if (registration != null) {
            registration.setLoadOnStartup(1);
            registration.addMapping("/app/*");
        }
    }
}
